/*** Trigger Name: UpdateQueryOfficeCode 
* Author: Accenture 
* Date: 06-Jun-2011 
* Requirement/Project Name: iFulfill 
* Requirement Description: when the Office detail of user changes, update office code and office of all queries associated with that user. 
**/

trigger UpdateOfficeCode  on User (before update)
{
list<Queries__c> queriesList = new list<Queries__c>();   
Map<id,user> queriesMap = new Map<id,user>();
set<Id> Userset = New Set<Id>();
 if (Trigger.isUpdate)
 {
   for(User userUpdateRecord :trigger.new)
     {           
         if(userUpdateRecord.SFA_Office__c != Trigger.oldMap.get(userUpdateRecord.id).SFA_Office__c)
           {              
            queriesMap.put(userUpdateRecord.id, userUpdateRecord);
            Userset.add(userUpdateRecord .Id);  
           }
     }
 }
 List<queries__C> QSupdate=[select Id,Office__c,Office_Code__c,OwnerId from queries__c where ownerID IN: Userset AND Office_Code__c!=null AND Office__c != null];
 for(queries__c QS:QSupdate)
 {                                     
     QS.Office_Code__c = queriesMap.get(QS.ownerid).SFA_Office__c; 
     QS.Office__c = queriesMap.get(QS.ownerid).SFA_Office_Name__c;
     queriesList.add(QS);        
 }   
 
try{
 if(queriesList.size()>0)
 {
 update queriesList;
 }             
 }
 catch(Exception e)
 {       
        
  GeneralConstants.mailAnyExceptionToMe('UpdateOfficeCode', 'Update office code' , e);    
 }
  }